package main

import (
	"context"
	"etcd-discovery/pkg/discovery"
	pb "etcd-discovery/proto"
	"log"
	"net"
	"strconv"

	"github.com/google/uuid"
	"google.golang.org/grpc"
)

const (
	appID = "sv2"
	PORT  = "9021"
)

type Sv2Service struct {
	UUID string
}

func (s *Sv2Service) Sv2Concat(ctx context.Context, r *pb.Sv2Request) (*pb.Sv2Response, error) {
	return &pb.Sv2Response{Response: s.UUID + ":" + r.Request}, nil
}

func main() {
	dis := discovery.New(&discovery.Config{
		Nodes: []string{
			"127.0.0.1:2379",
		},
		Prefix: "default",
		Lease: 3,
	})
	server := grpc.NewServer()
	sv2 := NewSv2Service()
	pb.RegisterSv2ServiceServer(server, sv2)
	lis, err := net.Listen("tcp", ":"+PORT)
	if err != nil {
		log.Fatalf("net.Listen err: %v", err)
	}
	dis.Register(&discovery.Instance{
		AppID: appID,
		Hostname: sv2.UUID,
		Addrs: []string{
			"grpc://" + "127.0.0.1" + ":" + PORT,
		},
		Metadata: map[string]string{
			"weight":  strconv.FormatInt(10, 10),
		},
	})
	server.Serve(lis)
}

func NewSv2Service() *Sv2Service {
	var sv2 Sv2Service
	uuid := uuid.New().String()
	sv2.UUID = uuid
	return &sv2
}
